package com.itzjc.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itzjc.domain.entity.Result;
import com.itzjc.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登录拦截器规则类
 *
 * @className: LoginInterceptor
 * @date: 2021-06-04 16:27
 **/
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 进入controller之前的拦截，检查有无token
     *
     * @param request
     * @param response
     * @param handler
     * @return:
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            //token一般在请求头中获取，如果没有就去体中找，体中还没有就是没有了
            String accesToken = request.getHeader("token");
            if (null == accesToken) {
                accesToken = request.getParameter("token");

            }
            //所有get请求携带的参数都写在info中，统一获取
            String accesGetInfo=request.getParameter("info");
            if (StringUtils.isNotBlank(accesToken)) {
                //解析token
                Claims claims = JWTUtils.checkJWT(accesToken);
                if (null == claims) {
                    //告知登录时效过了
                    sendJsonMessage(response, "登录失效,请重新登录");
                    return false;
                }
                Integer id = (Integer) claims.get("id");
                String name = (String) claims.get("name");
                request.setAttribute("user_id", id);
                request.setAttribute("name", name);
                request.setAttribute("info",accesGetInfo);
                return true;
            }
        } catch (Exception e) {
        }
        sendJsonMessage(response, "登录过期，请重新登录");

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * 由于此处只是拦截器不能像controller一样返回json数据，所以写一个返回json数据的方法
     *
     * @param response
     * @param
     * @return:
     **/
    public static void sendJsonMessage(HttpServletResponse response,String json) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print(json);
            writer.close();
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
